"""Helpers for the node code."""

import commands
import datetime
import logging
import os
import re
import psutil
import textwrap
import yaml
from gaweb import common


def get_system_info_text():
    """Returns a formatted block of text describing system info."""
    cpu_percent = '%.2f%%' % psutil.cpu_percent()

    text = textwrap.dedent("""
        Node Statistics
        ---------------
        CPU: %(cpu_percent)s
        Num Processes: %(num_processes)d
        Hostname: %(hostname)s
    """).strip() % {'cpu_percent': cpu_percent,
                    'num_processes': len(psutil.get_pid_list()),
                    'hostname': commands.getoutput('hostname'),
                    }
    return text


def handle_to_dict(handle, filter=False):
    """Converts a grads.GaHandle to a dictionary.
    
    If filter is set to true, also filters out handle values that don't directly
    convert to JSON.
    """
    valid_value = lambda vv: isinstance(vv, (tuple, list, int, float, basestring))
    is_iterable = lambda vv: isinstance(vv, (tuple, list))        

    d = {}
    
    for k, v in handle.__dict__.iteritems():
        if filter and not valid_value(v) or (is_iterable(v) and not all(valid_value(vv) for vv in v)):
            continue            
        d[k] = v
            
    return d


def patch_path():
    """Adds /opt/opengrads to $PATH"""
    os.environ['PATH'] = '/opt/opengrads:' + os.environ['PATH']


def read_config(fname='node.yaml', **kwargs):
    """Read the node config files."""
    return common.read_config(fname, **kwargs)


